from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views.generic.edit import CreateView
from django.http import JsonResponse
from .models import JoinInformation
from .forms import JoinInformationForm
import json

@method_decorator(csrf_exempt, name='dispatch')
class JoinApplicationCreateView(CreateView):
    model = JoinInformation
    form_class = JoinInformationForm
    template_name = None

    def post(self, request, *args, **kwargs):
        # 解析 JSON 数据
        try:
            data = json.loads(request.body.decode('utf-8'))
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': '数据格式错误'}, status=400)
        form = self.form_class(data)
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        self.object = form.save()
        return JsonResponse({
            'status': 'success',
            'message': '加盟申请提交成功',
            'data': {
                'id': self.object.id,
                'name': self.object.name
            }
        }, status=201)

    def form_invalid(self, form):
        errors = {}
        for field, field_errors in form.errors.items():
            errors[field] = [{'message': str(error), 'code': ''} for error in field_errors]
        # 处理非字段错误
        if form.non_field_errors():
            errors['__all__'] = [{'message': str(error), 'code': ''} for error in form.non_field_errors()]
        return JsonResponse({
            'status': 'error',
            'errors': errors
        }, status=400)